package com.bruce.asurada.sso.controller;

import com.bruce.asurada.common.Result;
import com.bruce.asurada.sso.constants.TokenConstants;
import com.bruce.asurada.common.dto.PhoneCodeLoginDTO;
import com.bruce.asurada.common.dto.TokenDTO;
import com.bruce.asurada.common.dto.UserInfoDto;
import com.bruce.asurada.common.dto.UserLoginDto;
import com.bruce.asurada.sso.service.SsoService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;


/**
 * SSO服务端控制器
 * 提供单点登录认证服务
 * 
 * @author Bruce
 */
@Slf4j
@RestController
@RequestMapping("/sso")
public class SsoController {

    @Autowired
    private SsoService ssoService ;



    /**
     * 生成授权码
     */
    @PostMapping("/generateAuthCode")
    public Result<String> generateAuthCode(@Validated @RequestBody UserLoginDto loginDto) {
        try {
            String authCode = ssoService.generateAuthCode(loginDto) ;
            log.info("SSO获取授权码成功: {}", loginDto.getAccount());
            return Result.success("SSO获取授权码成功", authCode);
        } catch (Exception e) {
            log.error("SSO获取授权码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据授权码获取令牌
     * @param entity
     * @return
     */
    @PostMapping("/token")
    public Result<TokenDTO> getToken(@RequestBody UserLoginDto loginDto) {
        try {            
            TokenDTO tokenDTO = ssoService.generateTokens(loginDto);
            return Result.success("获取令牌成功",tokenDTO);
        } catch (Exception e) {
           log.error("SSO获取令牌失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    


    /**
     * 手机号和验证码登录
     */
    @PostMapping("/loginByPhoneAndCode")
    public Result<TokenDTO> loginByPhoneAndCode(@Validated @RequestBody  PhoneCodeLoginDTO loginDto){
        try {
            TokenDTO response = ssoService.loginByPhoneAndCode(loginDto);
            log.info("验证码登录成功，手机号: {}", loginDto.getPhone());
            return Result.success("验证码登录成功", response);
        } catch (Exception e) {
            log.error("验证码登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    /**
     * 验证令牌有效性
     * 客户端应用调用此接口验证用户令牌
     */
    @GetMapping("/verify")
    public Result<UserInfoDto> verifyToken(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            UserInfoDto userInfo = ssoService.validateToken(token);
            return Result.success("令牌验证成功", userInfo);
        } catch (Exception e) {
            log.error("令牌验证失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }


    /**
     * 验证verifyImSession令牌有效性
     * 客户端应用调用此接口验证用户令牌
     */
    @GetMapping("/verifyImSession")
    public Result<UserInfoDto> verifyImSession(HttpServletRequest request) {
        try {
            String imSessionToken = request.getHeader(TokenConstants.IM_SESSION_TOKEN_HEADER_NAME) ;
            UserInfoDto userInfo = ssoService.validateImSessionToken(imSessionToken);
            return Result.success("令牌验证成功", userInfo);
        } catch (Exception e) {
            log.error("令牌验证失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查用户登录状态
     * 客户端应用调用此接口检查用户是否已登录
     */
    @GetMapping("/check")
    public Result<Boolean> checkLoginStatus(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            boolean isValid = ssoService.checkToken(token);
            return Result.success("登录状态检查完成", isValid);
        } catch (Exception e) {
            log.error("检查登录状态失败: {}", e.getMessage());
            return Result.success("登录状态检查完成", false);
        }
    }

    /**
     * SSO登出
     * 客户端应用调用此接口进行统一登出
     */
    @GetMapping("/logout")
    public Result<Void> ssoLogout(HttpServletRequest request) {
        try {
            String accessToken = request.getHeader(TokenConstants.ACCESS_TOKEN_HEADER_NAME) ;
            String refreshToken = request.getHeader(TokenConstants.REFRESH_TOKEN_HEADER_NAME) ;
            String imSessionToken = request.getHeader(TokenConstants.IM_SESSION_TOKEN_HEADER_NAME) ;
            String imAccessToken = request.getHeader(TokenConstants.IM_ACCESS_TOKEN_HEADER_NAME) ;
            TokenDTO tokenDTO = TokenDTO.builder()
                    .accessToken(accessToken)
                    .refreshToken(refreshToken)
                    .imSessionToken(imSessionToken)
                    .imAccessToken(imAccessToken)
                    .build();
            ssoService.logout(tokenDTO);
            log.info("SSO登出成功,token: {}", accessToken);
            return Result.success();
        } catch (Exception e) {
            log.error("SSO登出失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 刷新令牌
     * 客户端应用调用此接口刷新过期的访问令牌
     */
    @GetMapping("/refresh")
    public Result<TokenDTO> refreshToken(HttpServletRequest request) {
        try {
            String refreshToken = getTokenFromRequest(request);
            TokenDTO response = ssoService.refreshToken(refreshToken);
            log.info("令牌刷新成功");
            return Result.success("令牌刷新成功", response);
        } catch (Exception e) {
            log.error("令牌刷新失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 从请求中获取令牌
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        // 也支持从参数中获取token
        String token = request.getParameter("token");
        if (token == null) {
             throw new RuntimeException("未提供访问令牌");
          }
        return token;
    }
}